import { Inject, Injectable } from '@angular/core';
import { DA_SERVICE_TOKEN, ITokenService} from '@delon/auth';
import { HttpClient } from '@angular/common/http';
import { RET_CODE } from '@models';
import { MenuService } from '@delon/theme';
import { XConsole } from '@core/utils/XConsoleUtil';
import { checkArray, data2tree } from '@core/utils/utils';

@Injectable({
  providedIn: 'root'
})
export class SessionService {

  private _isLogin: boolean = null;

  private xConsole: XConsole;

  constructor(
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private _http: HttpClient,
    private menuService: MenuService,
  ) {
    this.xConsole = new XConsole();
  }

  get userNo() {
    return this.tokenService.get().userNo;
  }

  set userNo(value) {
    this.tokenService.set({
      ...this.tokenService.get(),
      userNo: value,
    })
  }

  getToken() {
    return this.tokenService.get().token;
  }

  clearToken() {
    this.tokenService.clear();
  }

  get isLoggedIn() {
    return this._isLogin;
  }


  setLoggedIn(value: boolean) {
    this._isLogin = value;
  }

  get loginUrl() {
    return this.tokenService.login_url;
  }

  get canRetry() {
    return !!this.tokenService.get().token;
  }

  get menuList() {
    return this.tokenService.get().menuList || [];
  }

  /**
   * 获取用户详情数据
   */
  checkUserDetail(): Promise<any> {
    return new Promise<any>((resolve, reject) => {
      this._http.get(`user-center/getSysUserDetail`,
      { params: {userNo: this.userNo}}).subscribe((_res: any) => {
        if (_res.retCode !== RET_CODE.SUCCESS) {
          reject('err'); // 异步操作失败的回调函数
        } else {
          this.setLoggedIn(true);
          const userInfo: any = {
            token: _res.element.access_token || 'token',
            userNo: _res.element.userNo,
            roleList: checkArray(_res.element.roleList),
          };
          this.tokenService.set(userInfo);
          this.setMenu(userInfo.roleList[0].menuList);
          resolve(_res); // 异步操作成功的回调函数
        }
      }, (err) => {
        console.error('[登录时获取用户详情异常] ===> ', err);
      });
    });
  }

  /**
   * 处理菜单数据
   * @param menuList 菜单数据数组
   */
  setMenu(menuList: Array<any>) {
    const tokenModel = this.tokenService.get();
    const tempList = menuList.map(item => {
      return {
        no: item.no,
        text: item.name,
        link: item.url,
        icon: {type: 'icon', value: item.menuIcon},
        menuFather: item.menuFather,
        menuOrder: item.menuOrder,
      }
    });
    const menuArray: Array<any> = data2tree(tempList);
    tokenModel.menuList = menuArray;
    this.tokenService.set(tokenModel);
    this.menuService.clear();
    const menu = {
      text: '测试1',
      children: menuArray
    };
    this.menuService.add([menu]);
  }

}
